import React, { useEffect, useRef, useState } from "react";
import { Card, Input, Button, Space, Row, Checkbox, message } from "antd";
import { login } from "../../http/user";
import store from "../../redux";
import { LOGIN_SUCCESS } from "../../redux/user/types";
import { MergeRouteComponentProps } from "../../router/types";
import "./index.scss";

interface IProps extends MergeRouteComponentProps {}

const Login: React.FC<IProps> = ({ history, location }) => {
    /**
     * 用户名
     */
    const [username, setUsername] = useState("admin");

    /**
     * 密码
     */
    const [password, setPassword] = useState("123456");

    /**
     * 副作用，监听事件
     */
    useEffect(() => {
        document.addEventListener("keydown", onKeyDown);
        return () => {
            document.removeEventListener("keydown", onKeyDown);
        };
    }, []);

    /**
     * 键盘事件
     * @param e
     */
    const onKeyDown = (e: KeyboardEvent) => {
        // 查看键盘键码
        console.log(e);
        if (e.code === "Enter") {
            onLoginClicked();
        }
    };

    /**
     * 登录事件处理函数
     */
    const onLoginClicked = async () => {
        // 登录
        const res = await login({ username, password });
        if (res.data.code !== 200) {
            console.log("res", res);
            message.error(res.data.message);
            return;
        }
        // 保存状态
        store.dispatch({
            type: LOGIN_SUCCESS,
            payload: {
                ...res.data.data,
                isLogin: true,
            },
        });
        // 存在重定向地址就使用，不存在就跳转到后端仪表盘页面
        history.push(location?.state?.redirect || "/admin/dashboard");
    };

    return (
        <div className="login">
            <Card title="登录考试系统" hoverable>
                <Space direction="vertical" size="large">
                    <Input
                        placeholder="请输入用户名，默认：admin"
                        onChange={(e) => setUsername(e.target.value)}
                    />

                    <Input.Password
                        placeholder="请输入密码，默认：123456"
                        onChange={(e) => setPassword(e.target.value)}
                    />

                    <Row justify="space-between">
                        <Checkbox>记住密码</Checkbox>
                        <Button type="link">忘记密码</Button>
                    </Row>

                    <Button type="primary" block onClick={onLoginClicked}>
                        登 陆
                    </Button>
                </Space>
            </Card>
        </div>
    );
};

export default Login;
